package com.xncoding.binfa;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class ConcurrencyLimit {
    private Semaphore semaphore;
    private ConcurrencyLimit() {    }
    public static ConcurrencyLimit create(int permits) {
        ConcurrencyLimit concurrencyLimit = new ConcurrencyLimit();
        concurrencyLimit.semaphore = new Semaphore(permits);
        return concurrencyLimit;
    }
    public void acquire() throws InterruptedException {
        this.semaphore.acquire();
    }
    public void release() {
        this.semaphore.release();
    }
    public boolean tryAcquire() {
        return this.semaphore.tryAcquire();
    }

    public static void main(String[] args) {
        ConcurrencyLimit limit = ConcurrencyLimit.create(5);
        ExecutorService executorService = Executors.newCachedThreadPool(
                new ThreadFactoryBuilder().setNameFormat("limit-%d").build());
        for (int i = 0; i < 10; i++) {
            executorService.execute(() -> {
                try {
                    limit.acquire();
                    System.out.println(Thread.currentThread().getName() + " START");
                    // 模拟内部耗时
                    TimeUnit.MILLISECONDS.sleep(new Random().nextInt(500));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    System.out.println(Thread.currentThread().getName() + " END");
                    limit.release();
                }
            });
        }

    }

}